package ufpb.compiladores.lexico.run;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Scanner;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author seminick
 */
public final class HtmlGenerator {
    
    private static final String[] RESERVADA = {
                                                    "Palavra Reservada"
                                               };
    
    static {
        
        Arrays.sort(RESERVADA);
    }
    
    private HtmlGenerator() {}
    
    public static String generateHtml(Document doc, File source) {
        
        StringBuilder htmldoc = new StringBuilder();
        StringBuilder aux = new StringBuilder();
        int linen = 0;

        try {
            
            Scanner scan = new Scanner(new FileInputStream(source));
            String line = null;
            int start = 0;
            NodeList nodes = doc.getFirstChild().getChildNodes();
            final int len = nodes.getLength();
            
            for (int i = 0; i < len; i++) {
                
                Node no = nodes.item(i);
                if (no.getNodeName().equals("Tabela")) {
                    
                    NodeList elementsn = no.getChildNodes();
                    final int lene = elementsn.getLength();
                    for (int j = 0; j < lene; j++) {

                        Node element = elementsn.item(j);
                        if (element.getNodeName().contains("Elemento")) {
                        
                            String token = element.getAttributes()
                                    .getNamedItem("token").getTextContent();
                            String desc = element.getAttributes()
                                    .getNamedItem("descricao").getTextContent();
                            if (line == null && scan.hasNextLine()) {

                                line = scan.nextLine();
                                linen++;
                                aux.delete(0, aux.length());
                                aux.append(line);
                            }
                            desc = desc.replaceAll("ó", "&oacute;");
                            
                            int inseri = aux.indexOf(token, start);
                            //Verifica se acha na linha ou tenho de pega outra
                            while (inseri == -1) {
                                
                                String toadd = aux.toString();
                                if (toadd.contains("\t")) {
                                        
                                    toadd = toadd.replaceAll("\t",
                                            "<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>");
                                }
                                htmldoc.append(linen).append(':').append(' ')
                                        .append(toadd).append("<br />");
                                if (scan.hasNextLine()) {

                                    line = scan.nextLine();
                                    linen++;
                                    aux.delete(0, aux.length());
                                    aux.append(line);
                                }
                                start = 0;
                                inseri = aux.indexOf(token, start);
                            }
                            
                            String css = null;
                            if (Arrays.binarySearch(RESERVADA, desc) < 0) {
                                
                                css = " class=\"identificador\" ";
                            } else {
                                css = " class=\"palavrachave\" ";
                                
                            }
                            
                            StringBuilder sin = new StringBuilder()
                                        .append("\n<span").append(css)
                                        .append("onmouseover='javascript:showDetail(\"")
                                        .append(desc).append("\");' onmouseout='javascript:showDetail(\"\");' />");
                            StringBuilder send = new StringBuilder().append("</span>");
                            int inserf = inseri + token.length() + sin.length();
                            aux.insert(inseri, sin.toString());
                            aux.insert(inserf, send.toString());
                            start = inseri;
                            start += token.length() + sin.length() + send.length();
                            
                            //String cp = line.toString();
                            //start += token.length();
                            
                        }
                    }
                }
            }
        } catch (Exception e) {
            //DO NOTHING
            e.printStackTrace();
        }
        
        htmldoc.append(linen).append(':').append(' ').append(aux.toString()).append('\n');
        insertHeader(htmldoc);
        htmldoc.append("<br /><br /><span id='detail'></span></body></html>");
        return htmldoc.toString();
    }
    
    private static void insertHeader(StringBuilder sb) {
        
        //TODO Trocar por um arquivo =D
        sb.insert(0, "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n"
                +"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
                + "\n<html>\n\t<head>\n\t\t<title>Analisador L&eacute;xico</title>"
                + "\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
                + "\n\t</head>\n<body>"
                + "\n\t<script type=\"text/javascript\">"
                + "\n\t\tfunction showDetail(det) {"
                + "\n\t\t\tdocument.getElementById(\"detail\").innerHTML = det;"
                + "\n\t\t}"
                + "\n\t</script>\n"
                + "\n\t<style type=\"text/css\">"
		+ "\n\t\t.palavrachave {color : #F00;}"
		+ "\n\t\t.palavrachave:hover {color : #00F;}"
		+ "\n\t\t.identificador:hover {color : #00F;}"
                + "\n\t</style>");
        
    }    
}
